package dbsync

import (
	"fmt"
	"database/sql"
	"strings"
)

//mysql
func doMysql(in *SyncRunIn) ([]Table,error) {
	fmt.Println(in)
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s",
		in.DbUser, in.DbPsd,in.DbHost, in.DbPort, in.DbName,
	)
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		return nil,err
	}

	var tables []Table

	//获取全部表名
	sql := "show tables"
	ts,err := db.Query(sql)
	if err != nil {
		return nil,err
	}

	for ts.Next() {
		var tName string
		ts.Scan(&tName)

		curTable := tName[len(in.TablePrefix):]
		var fields []Field

		//获取该表字段
		sql := "select COLUMN_NAME,COLUMN_TYPE,COLUMN_COMMENT from information_schema.COLUMNS where table_name = '"+tName+"' "
		fs,err := db.Query(sql)
		if err != nil {
			return nil,err
		}
		//call_tag_group
		for fs.Next() {
			var comment,fieldType,name string
			//var notnull bool
			fs.Scan(&name,&fieldType,&comment)
			//解析fieldType
			idx := strings.Index(fieldType," ")
			if idx < 0 {
				idx = strings.Index(fieldType,"(")
			}
			if idx>0 {
				fieldType = fieldType[:idx]
			}
			switch fieldType {
			case "char","varchar","tinytext","text","json":
				fieldType = "string"
			case "float","decimal":
				fieldType = "float64"
			case "tinyint","smallint","int":
				fieldType = "int"
			case "bigint":
				fieldType = "int64"
			case "","-":
				continue
			default:
				fmt.Println("暂不支持字段类型",tName,name,fieldType)
				return nil,fmt.Errorf("无效字段")
			}

			fields = append(fields,Field{
				Comment: comment,
				Type: fieldType,
				Name: name,
			})
		}
		tables = append(tables,Table{
			Name: curTable,
			Fields: fields,
		})
	}

	return tables,nil
}

